package com.gitee.magic.framework.base.rest;

import java.util.HashMap;
import java.util.Map;

import com.gitee.magic.core.json.JsonObject;

/**
 * @author start
 */
public class HttpRequest {

	/**
	 * 请求URL
	 */
	private String url;

	/**
	 * 获取生成的请求URL地址
	 */
	private String requestUrl;
	
	/**
	 * 请求方式
	 */
	private RequestMethodEnum requestMethod;
	
	/**
	 * Url参数
	 */
	private Map<String,String> urlParams=new HashMap<>();
	
	/**
	 * 请求头
	 */
	private Map<String,String> headers=new HashMap<>();
	
	/**
	 * 请求主体内容
	 */
	private String bodyContent;
	
	public HttpRequest(String url) {
		this(url,RequestMethodEnum.POST);
	}
	
	public HttpRequest(String url,RequestMethodEnum method) {
		this.url=url;
		this.requestMethod=method;
	}
	
	/**
	 * 设置URL参数
	 * @param name
	 * @param value
	 */
	public void setUrlParam(String name,String value) {
		urlParams.put(name, value);
	}
	
	public Map<String, String> getUrlParams() {
		return urlParams;
	}

	public void setUrlParams(Map<String, String> urlParams) {
		this.urlParams = urlParams;
	}

	/**
	 * 设置请求头参数
	 * @param name
	 * @param value
	 */
	public void setHeader(String name,String value) {
		headers.put(name, value);
	}
	
	public Map<String, String> getHeaders() {
		return headers;
	}
	
	public void setHeaders(Map<String, String> headers) {
		this.headers = headers;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	public String getRequestUrl() {
		if(requestUrl==null) {
			if(urlParams.isEmpty()) {
				requestUrl=getUrl();
			}else {
				requestUrl=HttpClient.urlQueryString(getUrl(), urlParams);
			}
		}
		return requestUrl;
	}

	public RequestMethodEnum getRequestMethod() {
		return requestMethod;
	}

	public void setRequestMethod(RequestMethodEnum requestMethod) {
		this.requestMethod = requestMethod;
	}
	
	/**
	 * 设置主体参数为URI&分隔
	 * @param body
	 */
	public void setUriBodyContent(Map<String,Object> body) {
		setBodyContent(HttpClient.bodyUrlEncodeString(body));
	}
	
	/**
	 * 设置主体参数为JSON体
	 * @param body
	 */
	public void setJsonBodyContent(Map<String,Object> body) {
		setBodyContent(new JsonObject(body).toString());
	}

	public String getBodyContent() {
		return bodyContent;
	}

	public void setBodyContent(String bodyContent) {
		this.bodyContent = bodyContent;
	}
	
}
